package collection;

import java.util.*;

/**
 * @author xiaoming
 * @version 1.0
 * @date 2019-03-02 16:10
 * 6.4 数组与集合
 **/
public class ArrayAndCollection {
    public static void main(String[] args) {

        String s = new String("");
        // 静态初始化
        String[] args2 = {"b","a"};
        args = args2;
        System.out.println(Arrays.toString(args));

        // 动态初始化
        String[] args3 = new String[2];
        args3[0] = "e";
        args3[1] = "f";
        // NegativeArraySizeException
        //String[] args4 = new String[-1];

        int[] ints = {3, 1, 5, 6, 7};
        // 排序
        Arrays.sort(ints);
        System.out.println(Arrays.toString(ints));
        // jdk 1.5
        // foreach遍历

        int[] ints2 = {3, 1, 5, 6, 7};
        Arrays.asList(ints2).stream().forEach(x -> System.out.println(x));
        Arrays.asList(ints2).stream().forEach(System.out::println);

        // 性能差,弃用
        Vector<String> stringVector = new Vector<>();

        //  数组转换为集合
        String[] args5 = new String[3];
        args5[0] = "one";
        args5[1] = "two";
        args5[2] = "three";

        List<String> stringList = Arrays.asList(args5);

        stringList.set(0, "oneList");
        // 修改成功转换后的集合, 原数组也随之改变了
        System.out.println(args5[0]);
        // 不能进行元素个数的修改
        // 抛出: UnsupportedOperationException
        //stringList.add("four");
        //stringList.remove(0);
        //stringList.clear();

        System.out.println(stringList.toString());
        args5[2] ="five";
        System.out.println(stringList.toString());

        // 集合转数组
        System.out.println("集合转数组");

        List<String> stringList1 = new ArrayList<String>(3);
        stringList1.add("one");
        stringList1.add("two");
        stringList1.add("three");

        // 泛型丢失, 无法使用String[] 接收无参方法返回的结果
        Object[] objectArray1 = stringList1.toArray();
        System.out.println(Arrays.asList(objectArray1));


        // stringArray2 数组长度小于stringList1
        String[] stringArray2 = new String[2];
        stringList1.toArray(stringArray2);
        // [null,null]
        System.out.println(Arrays.asList(stringArray2));

        // 长度相同
        String[] stringArray3 = new String[3];
        stringList1.toArray(stringArray3);
        // [one, two, three]
        System.out.println(Arrays.asList(stringArray3));



    }
}



